<script setup>
import { onLaunch, onShow } from "@dcloudio/uni-app";
import { useStore } from "vuex";
import { ApiGetUserInfo } from "./api/user";
import { ApiGetCityList, ApiReverseGeocode } from "./api/city";
import STORAGE_KEY from "./config/storageKey";
import { watch } from "vue";
import { loadAMap } from '@/utils/amap';
const $store = useStore();

onLaunch(() => {
	console.log('App Launch')
	uni.removeStorageSync(STORAGE_KEY.serverConf);
  	getUserInfo();
});


onShow(() => {
	console.log('App Show')
  getLocation();
});
/**
 * @Description: 获取用户信息
 * @return {*}
 */
const getUserInfo = async () => {
  const { error, result } = await ApiGetUserInfo();
  if (result) {
    $store.commit("setUserInfo", result);
  }
};

const getLocation = async () => {
  // 先从 store 拿 city（仅用于打印或兜底，不影响逻辑）
  const city = $store.state.city;
  console.log('当前城市:', city);

  // 等高德地图 SDK 加载完成
  const AMap = await loadAMap();

  AMap.plugin('AMap.Geolocation', function() {
    const geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
    });
    geolocation.getCurrentPosition(function (status, result) {
      if (status === 'complete') {
        console.log('高德定位成功', result.position); // GCJ-02
      } 
    });
  });

  try {
    const locationRes = await new Promise((resolve, reject) => {
      uni.getLocation({
        type: 'wgs84',
        success: resolve,
        fail: reject,
      });
    });

    const { latitude, longitude } = locationRes;

    // 获取城市列表
    const { error, result: cityList = [] } = await ApiGetCityList();
    if (error) throw new Error('城市列表获取失败');

    // 调你后端的逆地理接口
    // const { data } = await ApiReverseGeocode({ lat: latitude, lng: longitude });



    const reverseRes = await ApiReverseGeocode({ lat: latitude, lng: longitude });
console.log('ApiReverseGeocode 返回：', reverseRes);



    const cityInfo = {
      adcode: reverseRes.result.adcode,
      citycode: reverseRes.result.citycode,
      name: reverseRes.result.name,
      center: `${longitude},${latitude}`,
    };

    $store.commit('setCity', cityInfo);
    console.log('当前城市cityInfo:', cityInfo);

  } catch (err) {
    console.error('定位或城市数据获取失败:', err);
    $store.commit('setCity', {
      adcode: '000000',
      citycode: '',
      name: '未知城市',
      center: '',
    });
  }
};

</script>

<style>
/*每个页面公共css */
</style>
